// 插件->宿主小程序使用的api封装
const _plugin = requirePlugin("shop2cn-shopapis-plugin");   // 解决开发者工具启动时的加载问题
const config = require('./config')
const Event = require('./event')
const constDefine = require('./constDefine')

console.warn(`SHOP HOST LOADED! [${config.TAG}] VERSION [${config.SDK_VERSION}]! \n config detail:\n${JSON.stringify(config)}`)

module.exports.onLaunch = function(options) {
    console.log(`[${config.TAG}] onLaunch ${JSON.stringify(options)}`)

    const plugin = requirePlugin("shop2cn-shopapis-plugin");
    plugin.onLaunch(options)

    wx.nextTick(() => {
        this.getEventBus()
    })
}

module.exports.onShow = function(options) {
    console.log(`[${config.TAG}] onShow ${JSON.stringify(options)}`)

    const plugin = requirePlugin("shop2cn-shopapis-plugin");
    plugin.onShow(options)
    this.payUtil.onShow(options)
    if (options && options.referrerInfo && options.referrerInfo.extraData && options.referrerInfo.extraData.code == 1) {
        try {
            requirePlugin.async('shop2cn-shopcore-plugin').then(corePlugin => {
                options.checkPayResult = 1
                corePlugin.onShow(options)
            })
        } catch (error) {
            console.log(error)
        }
    }
}

module.exports.payUtil = {
    onShow(options) {
        if (options && options.referrerInfo) {
            var payResult = options.referrerInfo.extraData || null;
            if (this.thirdPayData && this.thirdPayData.orderId && payResult && payResult.hasOwnProperty('success')) {
                const plugin = requirePlugin("shop2cn-shopapis-plugin");
                plugin.payResult(payResult.success == 1, this.thirdPayData)
                this.thirdPayData = null
            }
        }
    },
    
    setThirdPayData(data) {
        this.thirdPayData = data;
    },

    checkOrderStatus(obj, cb) {
        if (this.thirdPayData) {
            const plugin = requirePlugin("shop2cn-shopapis-plugin");
            plugin.checkOrderStatus(obj, cb)
        }
    },
    payResult(success, obj) {
        const plugin = requirePlugin("shop2cn-shopapis-plugin");
        plugin.payResult(success, obj)
        this.thirdPayData = null
    }
}

module.exports.onHide = function() {
    console.log(`[${config.TAG}] onHide`)

    const plugin = requirePlugin("shop2cn-shopapis-plugin");
    plugin.onHide()
},

/**
 * Event Bus
 */
module.exports.getEventBus = function() {
    const app = getApp()
    if (!app) {
        return null
    }

    const varName = constDefine.SHOPPLUGIN_VARNAME_APP_EVENTBUS_NAME
    if (!app[varName]) {
        app[varName] = new Event()
    }

    return app[varName]
}

/**
* 插件sso授权，信息通过客户端传递
* @param {string} user_uuid - 宿主小程序用户的唯一ID，建议使用小程序的openid
* @param {Object} user_info - 用户信息对象，具体字段：{nickname:昵称，avatar:头像，mobile:手机号(可选)，mobile_area_code:手机号区号(可选)}
* @param {Object} sign_info - 签名信息，具体字段：sign:签名，timestamp:参与签名的时间戳(精确到秒)
* @param {bool} isforce - true：强制服务器验证，false：优先使用本地缓存
* @param {function} callback - 授权回调函数 function(code, msg)  code<0授权失败，>=0授权成功！注意：成功时需要宿主主动调用navigateBack
*/
module.exports.ssoPlugin = function(user_uuid, user_info, sign_info, isforce, cb) {
    console.log(`${config.TAG} SSO PLUGIN! user_uuid:${user_uuid}, userinfo:${JSON.stringify(user_info)}, sign: ${JSON.stringify(sign_info)}, isforce:${isforce}`)
    
    const key = '__PLUGIN_HOST_SSO_USERID__'
    try { wx.setStorageSync(key, user_uuid) } catch (e) { }

    const plugin = requirePlugin("shop2cn-shopapis-plugin");
    plugin.ssoPlugin(user_uuid, user_info, sign_info, isforce, cb)
}

/**
* 插件退出登录
*/
module.exports.logout = function() {
    const plugin = requirePlugin("shop2cn-shopapis-plugin");
    plugin.logout()
}

/**
* 检查订单支付状态
* @param {object} obj - 订单支付信息
*/
module.exports.checkOrderStatus = function(obj) {
    const plugin = requirePlugin("shop2cn-shopapis-plugin");
    plugin.checkOrderStatus(obj)
}

// 跳转到tab首页
module.exports.gotoTabIndex = function() {
    const url = `plugin-private://${config.SHOPTAB_PLUGIN_ID}/pages/shoptab/shoptab`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoTabIndex ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到购物车
module.exports.gotoCart = function() {
    const url = `plugin-private://${config.SHOPCORE_PLUGIN_ID}/subPackage/pages/shoppingcart/shoppingcart`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoCart ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到tab购物车
module.exports.gotoTabCart = function() {
    const url = `plugin-private://${config.SHOPTAB_PLUGIN_ID}/pages/shoptab/shoptab?page=cart`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoTabCart ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到订单列表
// tabIndex: 对应的tab编号，从0开始
module.exports.gotoOrderList = function(tabIndex = 0) {
    const url = `plugin-private://${config.SHOPCORE_PLUGIN_ID}/subPackage/pages/myorderlist/myorderlist?tabIndex=${tabIndex}`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoOrderList ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到tab订单列表
module.exports.gotoTabOrderList = function() {
    const url = `plugin-private://${config.SHOPTAB_PLUGIN_ID}/pages/shoptab/shoptab?page=order`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoOrderList ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到商品详情
module.exports.gotoProduct = function(pid) {
    const url = `plugin-private://${config.SHOPCORE_PLUGIN_ID}/pages/item/item?productId=${pid}`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoProduct ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到全部商品
module.exports.gotoProdAll = function() {
    const url = `plugin-private://${config.SHOPCORE_PLUGIN_ID}/pages/prodall/prodall`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoProdAll ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到我的收藏
module.exports.gotoLikes = function() {
    const url = `/shopPlugin/shopcore/pages/webView/webView?url=${encodeURIComponent(`https://${config.H5_HOST}/shop/${config.SHOP_ID}/mycollection`)}&isHideShareMenu=1`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoLikes ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到我的优惠券
module.exports.gotoCoupons = function() {
    const url = `/shopPlugin/shopcore/pages/webView/webView?url=${encodeURIComponent(`https://${config.H5_HOST}/shop/${config.SHOP_ID}/coupons`)}&isHideShareMenu=1`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoCoupons ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到分类详情页
module.exports.gotoCategoryDetail = function(item, partId) {
    let url = `plugin-private://${config.SHOPCORE_PLUGIN_ID}/subPackage/pages/search/search?item=${encodeURIComponent(JSON.stringify(item))}`
    if (partId) {
        url += `&partId=${partId}`
    }
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoCategoryDetail ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到拼团列表
module.exports.gotoTuanList = function() {
    const url = `/shopPlugin/shoptab/pages/tuan/tuan?url=${encodeURIComponent(`https://${config.H5_HOST}/tuan/${config.SHOP_ID}/list`)}`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoCoupons ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}

// 跳转到我的拼团列表
module.exports.gotoMyTuanList = function() {
    const url = `/shopPlugin/shoptab/pages/tuan/tuan?url=${encodeURIComponent(`https://${config.H5_HOST}/tuan/${config.SHOP_ID}/mylist`)}`
    wx.navigateTo({
        url,
        fail: err => {
            console.error(`${config.TAG} gotoCoupons ERROR! url:${url}, err: ${JSON.stringify(err)}`)
        }
    })
}